#/usr/bin/perl                                                                                                                           

# input: .frequencies - describes change of frequencies of clones over time
# output: .fixations.log - describes fixations of survival, repro, mut alleles

# warning - no fixation of mutator locus

$name = "sim";
$neut_loci = 100; # 0 through 99
$repr_loci = 5;
$surv_loci = 5;
$fixation_threshold = 0.90;


for $sw ($ARGV[0]..$ARGV[1]){

    my %clonefreq =();
    my $day = 182; 
    my $generation;
    my $firstline = 1;
    my $fixations = 0;
    my $survfixations = 0;
    my $reprfixations = 0;
    open (out,">$name$sw/$name$sw.fixations.log");
    open (in,"$name$sw/$name$sw.frequencies");
    while(<in>){
	chomp;
	@row=split(/\,/);
	if($firstline){
	    $generation=$row[4];
	    $firstline=0;
	}
	# Store a clone that has fixed in a hash
	if($row[0]!=0){ # ignore wild type clone
	    if(!defined($clonefreq{$row[0]})){
		# total fixations = neutral + surv + repro
		if($row[2]>$fixation_threshold){
		    $clonefreq{$row[0]}=1;
		    $fixations++;
		}
		if($row[2]>$fixation_threshold&&$row[3]>$neut_loci-1&&$row[3]<$neut_loci+$surv_loci){
		    #$clonefreq{$row[0]}=1;
		    $survfixations++;
		}
		if($row[2]>$fixation_threshold&&$row[3]>$neut_loci+$surv_loci-1){
		    #$clonefreq{$row[0]}=1;
		    $reprfixations++;
		}
	    }
	}
	if($row[1]!=$day){
	    print out "$day,$fixations,$survfixations,$reprfixations,$generation\n";
	    $fixations = 0;
	    $survfixations = 0;
	    $reprfixations = 0;
	    if($day==7280){
		$day=7300;
	    } else {
		$day+=182;
	    }
	    $generation=$row[4];
	}
    }
    print out "$day,$fixations,$survfixations,$reprfixations,$generation\n";    
    close out;
    close in;
    print STDERR "Processed sweep $sw\n";
}

